{% extends "base.html" %}

{% block title %}用户登录 - 个人工具网站集{% endblock %}

{% block content %}
<div class="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-8">
        <div class="bg-white rounded-xl shadow-lg p-8">
            <!-- 标题 -->
            <div class="text-center mb-8">
                <div class="mx-auto h-12 w-12 bg-blue-100 rounded-full flex items-center justify-center mb-4">
                    <i class="fas fa-sign-in-alt text-blue-600 text-xl"></i>
                </div>
                <h2 class="text-3xl font-bold text-gray-900 mb-2">欢迎回来</h2>
                <p class="text-gray-600">登录您的账户，继续使用工具集</p>
            </div>
            
            <!-- 登录表单 -->
            <form method="POST" id="loginForm" class="space-y-6">
                <div>
                    <label for="username" class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-user mr-2"></i>用户名或邮箱
                    </label>
                    <input type="text" id="username" name="username" required 
                           class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
                           placeholder="请输入用户名或邮箱">
                </div>
                
                <div>
                    <label for="password" class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-lock mr-2"></i>密码
                    </label>
                    <div class="relative">
                        <input type="password" id="password" name="password" required 
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors pr-12"
                               placeholder="请输入密码">
                        <button type="button" onclick="togglePassword('password')" 
                                class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600">
                            <i class="fas fa-eye" id="password-eye"></i>
                        </button>
                    </div>
                </div>
                
                <!-- 记住我和忘记密码 -->
                <div class="flex items-center justify-between">
                    <div class="flex items-center">
                        <input type="checkbox" id="remember" name="remember" 
                               class="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500">
                        <label for="remember" class="ml-2 text-sm text-gray-600">
                            记住我
                        </label>
                    </div>
                    <a href="{{ url_for('forgot_password') }}" class="text-sm text-blue-600 hover:text-blue-500 underline">
                        忘记密码？
                    </a>
                </div>
                
                <!-- 提交按钮 -->
                <button type="submit" id="submitBtn" 
                        class="w-full bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors font-medium">
                    <span id="submitText">
                        <i class="fas fa-sign-in-alt mr-2"></i>登录
                    </span>
                    <span id="submitLoading" class="hidden">
                        <i class="fas fa-spinner fa-spin mr-2"></i>登录中...
                    </span>
                </button>
            </form>
            
            <!-- 注册链接 -->
            <div class="mt-6 text-center">
                <p class="text-sm text-gray-600">
                    还没有账户？
                    <a href="{{ url_for('register') }}" class="text-blue-600 hover:text-blue-500 font-medium underline">
                        立即注册
                    </a>
                </p>
            </div>
            
            <!-- 社交登录 -->
            <div class="mt-6">
                <div class="relative">
                    <div class="absolute inset-0 flex items-center">
                        <div class="w-full border-t border-gray-300"></div>
                    </div>
                    <div class="relative flex justify-center text-sm">
                        <span class="px-2 bg-white text-gray-500">或使用以下方式登录</span>
                    </div>
                </div>
                
                <div class="mt-6 grid grid-cols-2 gap-3">
                    <button class="w-full inline-flex justify-center py-2 px-4 border border-gray-300 rounded-lg shadow-sm bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 transition-colors">
                        <i class="fab fa-github text-lg"></i>
                        <span class="ml-2">GitHub</span>
                    </button>
                    <button class="w-full inline-flex justify-center py-2 px-4 border border-gray-300 rounded-lg shadow-sm bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 transition-colors">
                        <i class="fab fa-google text-lg"></i>
                        <span class="ml-2">Google</span>
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 快速访问 -->
        <div class="bg-white rounded-xl shadow-lg p-6 mt-6">
            <h3 class="text-lg font-semibold text-gray-900 mb-4 text-center">
                <i class="fas fa-rocket text-blue-500 mr-2"></i>快速访问
            </h3>
            <div class="grid grid-cols-2 gap-4">
                <a href="{{ url_for('index') }}" class="flex items-center p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
                    <div class="flex-shrink-0 w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
                        <i class="fas fa-home text-blue-600 text-sm"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium text-gray-900">首页</p>
                        <p class="text-xs text-gray-500">浏览工具</p>
                    </div>
                </a>
                
                <a href="{{ url_for('tools_category', category='开发助手') }}" class="flex items-center p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
                    <div class="flex-shrink-0 w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
                        <i class="fas fa-code text-green-600 text-sm"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium text-gray-900">开发工具</p>
                        <p class="text-xs text-gray-500">编程助手</p>
                    </div>
                </a>
                
                <a href="{{ url_for('tools_category', category='图像工具') }}" class="flex items-center p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
                    <div class="flex-shrink-0 w-8 h-8 bg-purple-100 rounded-full flex items-center justify-center">
                        <i class="fas fa-image text-purple-600 text-sm"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium text-gray-900">图像处理</p>
                        <p class="text-xs text-gray-500">图片工具</p>
                    </div>
                </a>
                
                <a href="{{ url_for('tools_category', category='小游戏') }}" class="flex items-center p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
                    <div class="flex-shrink-0 w-8 h-8 bg-red-100 rounded-full flex items-center justify-center">
                        <i class="fas fa-gamepad text-red-600 text-sm"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium text-gray-900">小游戏</p>
                        <p class="text-xs text-gray-500">休闲娱乐</p>
                    </div>
                </a>
            </div>
        </div>
        
        <!-- 安全提示 -->
        <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
            <div class="flex">
                <div class="flex-shrink-0">
                    <i class="fas fa-shield-alt text-yellow-600"></i>
                </div>
                <div class="ml-3">
                    <h3 class="text-sm font-medium text-yellow-800">安全提示</h3>
                    <div class="mt-2 text-sm text-yellow-700">
                        <ul class="list-disc list-inside space-y-1">
                            <li>请勿在公共设备上保存登录状态</li>
                            <li>定期更换密码以保护账户安全</li>
                            <li>如发现异常登录，请及时联系我们</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// 表单验证和交互
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('loginForm');
    const usernameInput = document.getElementById('username');
    const passwordInput = document.getElementById('password');
    
    // 表单提交
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        
        if (validateForm()) {
            submitForm();
        }
    });
    
    // 回车键快速登录
    [usernameInput, passwordInput].forEach(input => {
        input.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                form.dispatchEvent(new Event('submit'));
            }
        });
    });
    
    // 自动填充检测
    setTimeout(() => {
        if (usernameInput.value) {
            usernameInput.classList.add('border-green-500');
        }
        if (passwordInput.value) {
            passwordInput.classList.add('border-green-500');
        }
    }, 1000);
});

function togglePassword(inputId) {
    const input = document.getElementById(inputId);
    const eye = document.getElementById(inputId + '-eye');
    
    if (input.type === 'password') {
        input.type = 'text';
        eye.className = 'fas fa-eye-slash';
    } else {
        input.type = 'password';
        eye.className = 'fas fa-eye';
    }
}

function validateForm() {
    const username = document.getElementById('username').value.trim();
    const password = document.getElementById('password').value;
    
    if (!username) {
        showFieldError(document.getElementById('username'), '请输入用户名或邮箱');
        return false;
    }
    
    if (!password) {
        showFieldError(document.getElementById('password'), '请输入密码');
        return false;
    }
    
    return true;
}

function showFieldError(field, message) {
    // 移除现有错误信息
    const existingError = field.parentNode.querySelector('.field-error');
    if (existingError) {
        existingError.remove();
    }
    
    // 添加新错误信息
    const errorDiv = document.createElement('div');
    errorDiv.className = 'field-error text-sm text-red-600 mt-1';
    errorDiv.textContent = message;
    field.parentNode.appendChild(errorDiv);
    
    // 添加错误样式
    field.classList.add('border-red-500');
    field.classList.remove('border-gray-300');
    
    // 聚焦到错误字段
    field.focus();
}

function hideFieldError(field) {
    const errorDiv = field.parentNode.querySelector('.field-error');
    if (errorDiv) {
        errorDiv.remove();
    }
    
    field.classList.remove('border-red-500');
    field.classList.add('border-gray-300');
}

function submitForm() {
    const submitBtn = document.getElementById('submitBtn');
    const submitText = document.getElementById('submitText');
    const submitLoading = document.getElementById('submitLoading');
    
    // 显示加载状态
    submitBtn.disabled = true;
    submitText.classList.add('hidden');
    submitLoading.classList.remove('hidden');
    
    // 获取表单数据
    const formData = new FormData(document.getElementById('loginForm'));
    const loginData = {
        username: formData.get('username'),
        password: formData.get('password')
    };
    
    // 发送JSON请求
    fetch('{{ url_for("login") }}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(loginData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 登录成功
            showSuccessMessage('登录成功！正在跳转...');
            
            // 跳转到目标页面
            setTimeout(() => {
                const redirectUrl = new URLSearchParams(window.location.search).get('next') || '{{ url_for("index") }}';
                window.location.href = redirectUrl;
            }, 1500);
        } else {
            // 登录失败
            showErrorMessage(data.message || '登录失败，请检查用户名和密码');
            
            // 如果是邮箱未验证
            if (data.error_type === 'email_not_verified') {
                setTimeout(() => {
                    if (confirm('您的邮箱尚未验证，是否重新发送验证邮件？')) {
                        resendVerificationEmail(data.email);
                    }
                }, 2000);
            } else {
                // 如果是用户名或密码错误，提供重置密码选项
                setTimeout(() => {
                    showPasswordResetOptions();
                }, 2000);
            }
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showErrorMessage('网络错误，请重试');
    })
    .finally(() => {
        // 恢复按钮状态
        submitBtn.disabled = false;
        submitText.classList.remove('hidden');
        submitLoading.classList.add('hidden');
    });
}

function resendVerificationEmail(email) {
    fetch('{{ url_for("resend_verification") }}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email: email })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showSuccessMessage('验证邮件已重新发送，请检查您的邮箱');
        } else {
            showErrorMessage(data.message || '发送失败，请稍后重试');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showErrorMessage('网络错误，请重试');
    });
}

function showPasswordResetOptions() {
    // 创建模态框
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
    modal.innerHTML = `
        <div class="bg-white rounded-lg p-6 max-w-md w-full mx-4">
            <h3 class="text-lg font-semibold mb-4 text-gray-800">登录失败</h3>
            <p class="text-gray-600 mb-6">用户名或密码错误，您可以选择以下操作：</p>
            
            <div class="space-y-3">
                <button onclick="showResendVerificationOption()" 
                        class="w-full bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 rounded-lg transition duration-200">
                    <i class="fas fa-envelope mr-2"></i>重新发送验证邮件
                </button>
                
                <button onclick="goToForgotPassword()" 
                        class="w-full bg-green-500 hover:bg-green-600 text-white font-medium py-2 px-4 rounded-lg transition duration-200">
                    <i class="fas fa-key mr-2"></i>重置密码
                </button>
                
                <button onclick="closeModal()" 
                        class="w-full bg-gray-500 hover:bg-gray-600 text-white font-medium py-2 px-4 rounded-lg transition duration-200">
                    <i class="fas fa-times mr-2"></i>取消
                </button>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // 点击背景关闭模态框
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            closeModal();
        }
    });
}

function showResendVerificationOption() {
    closeModal();
    const username = document.getElementById('username').value;
    if (username) {
        if (confirm('是否重新发送验证邮件到您的注册邮箱？')) {
            resendVerificationEmail(username);
        }
    } else {
        showErrorMessage('请先输入用户名');
    }
}

function goToForgotPassword() {
    closeModal();
    window.location.href = '{{ url_for("forgot_password") }}';
}

function closeModal() {
    const modal = document.querySelector('.fixed.inset-0.bg-black');
    if (modal) {
        modal.remove();
    }
}

function showSuccessMessage(message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = 'fixed top-4 right-4 bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg z-50';
    alertDiv.innerHTML = `<i class="fas fa-check-circle mr-2"></i>${message}`;
    
    document.body.appendChild(alertDiv);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}

function showErrorMessage(message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = 'fixed top-4 right-4 bg-red-500 text-white px-6 py-3 rounded-lg shadow-lg z-50';
    alertDiv.innerHTML = `<i class="fas fa-exclamation-circle mr-2"></i>${message}`;
    
    document.body.appendChild(alertDiv);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}

// 键盘快捷键
document.addEventListener('keydown', function(e) {
    // Ctrl+Enter 快速登录
    if (e.ctrlKey && e.key === 'Enter') {
        document.getElementById('loginForm').dispatchEvent(new Event('submit'));
    }
    
    // ESC 清除错误信息
    if (e.key === 'Escape') {
        document.querySelectorAll('.field-error').forEach(error => error.remove());
        document.querySelectorAll('.border-red-500').forEach(field => {
            field.classList.remove('border-red-500');
            field.classList.add('border-gray-300');
        });
    }
});

// 自动保存用户名
const usernameInput = document.getElementById('username');
if (localStorage.getItem('saved_username')) {
    usernameInput.value = localStorage.getItem('saved_username');
}

usernameInput.addEventListener('blur', function() {
    if (this.value.trim()) {
        localStorage.setItem('saved_username', this.value.trim());
    }
});
</script>
{% endblock %}